package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

//新增
func Addrticle(c *gin.Context) {
	var article model.Article
	c.ShouldBindJSON(&article)
	code := model.AddArticle(&article)
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message":errmsg.GetErrorMsg(code),
	})
}

//编辑
func EditArticle(c *gin.Context) {
	var data model.Article
	id, _ := strconv.Atoi(c.Param("id"))
	_ = c.ShouldBindJSON(&data)
	code := model.EditArticle(id, &data)
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message":errmsg.GetErrorMsg(code),
	})
}

//删除article
func DeleteArticle(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteArticle(id)
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message":errmsg.GetErrorMsg(code),
	})
}

//查询所有文章
func GetArticles(c *gin.Context) {
	//pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	//pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	//if pageSize == 0 {
	//	pageSize = -1
	//}
	//if pageNum == 0 {
	//	pageNum = -1
	//}
	datas, code := model.GetArticles()
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message":errmsg.GetErrorMsg(code),
		"datas":datas,

	})
}

//查询单个文章
func GetArticle(c *gin.Context) {
	id ,_:= strconv.Atoi(c.Param("id"))
	data, code := model.GetArticle(id)
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message":errmsg.GetErrorMsg(code),
		"data":data,
	})
}

//查询分类下的文章
func GetCategoryArticles(c *gin.Context) {
	cid ,_:= strconv.Atoi(c.Query("cid"))
	fmt.Println("cid: ", cid)
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	datas, code := model.GetCategoryArticle(cid, pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H {
		"code":code,
		"message":errmsg.GetErrorMsg(code),
		"datas":datas,
	})
}